package com.antcom.antread.antreaddatacrawl.util;

import com.antcom.antread.common.core.exception.CustomException;
import com.antcom.antread.common.core.text.PropertiesUtil;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.springframework.util.DigestUtils;

import java.io.IOException;
import java.util.Date;
import java.util.Random;

/**
 * 发送请求
 *
 * @author 中国蚂蚁技术有限公司
 */
public class SendRequestUtil {

    /**
     * 获取当前时间
     */
    private static Date date = new Date();

    /**
     * 字符集
     */
    private static final String CHARSET_ENCODING="UTF-8";

    /**
     * 设置随机数
     */
    private static Random random = new Random();

    /**
     * 配置超时时间
     */
    private static RequestConfig requestConfig = null;
    static {
        // 设置请求和传输超时时间
        requestConfig = RequestConfig.custom().setSocketTimeout(20000).setConnectTimeout(20000).build();
    }

    /**
     * 获取服务器时间戳
     * @return time
     */
    public static String getTimestamp(){
        //获取时间戳路径
        String timeUrl = PropertiesUtil.getDocking("TIME_URL");
        return sendHttpClientGET(timeUrl);
    }

    /**
     * 获取token
     * @return token
     */
    public static String getToken(){
        String timestampOne = getTimestamp();
        String timestampTwo = getTimestamp();
        String param = "himalaya-"+timestampOne;

        String digestParam = DigestUtils.md5DigestAsHex(param.getBytes());
        //获取随机数 100以内
        int num1 = random.nextInt(99) + 1;
        int num2 = random.nextInt(99) + 1;
        //拼接
        StringBuilder xmSign = new StringBuilder();
        xmSign.append(digestParam);
        xmSign.append("("+num1+")");
        xmSign.append(timestampOne);
        xmSign.append("("+num2+")");
        xmSign.append(timestampTwo);
        return xmSign.toString();
    }

    /**
     * 使用httpclient GET 发送请求
     * @param url 路径
     * @return response 响应
     */
    public static String sendHttpClientGET(String url){

        //模拟浏览器
        try {
            //模拟浏览器
            HttpClient httpClient = HttpClientBuilder.create().build();
            //设置请求头
            HttpGet httpGet = new HttpGet(url);
            httpGet.setHeader("content-type","application/x-www-form-urlencoded;charset=UTF-8");
            httpGet.setHeader("user-agent","Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4128.3 Safari/537.36");
//            httpGet.setHeader("xm-sign",token);
            HttpResponse  response = httpClient.execute(httpGet);
            if (response.getStatusLine().getStatusCode()==200){
                HttpEntity httpEntity = response.getEntity();
                String content= EntityUtils.toString(httpEntity,CHARSET_ENCODING);
                return content;
            }else {
                throw new CustomException("GET请求异常:500");
            }
        } catch (Exception e) {
            throw new CustomException("GET请求异常");
        }
    }

    /**
     * 使用httpclient POST 发送请求
     * @param url 路径
     * @param param 参数
     * @return response 响应
     */
    public static String sendHttpClientPOST(String url,String param){
        //模拟浏览器
        try {
            //模拟浏览器
            HttpClient httpClient = HttpClientBuilder.create().build();
            //设置请求头
            HttpPost httpPost = new HttpPost(url);
            httpPost.setConfig(requestConfig);
            StringEntity entity = new StringEntity(param, CHARSET_ENCODING);
            entity.setContentEncoding(CHARSET_ENCODING);
            entity.setContentType("application/json");
            httpPost.setEntity(entity);
            HttpResponse response = httpClient.execute(httpPost);
            if (response.getStatusLine().getStatusCode()==200){
                HttpEntity httpEntity = response.getEntity();
                String content= EntityUtils.toString(httpEntity,CHARSET_ENCODING);
                return content;
            }else {
                throw new CustomException("POST请求异常:500");
            }
        } catch (Exception e) {
            throw new CustomException("POST请求异常");
        }
    }

    /**
     * 自定义响应
     */
    private static ResponseHandler<ResponseResult> responseHandler = new ResponseHandler<ResponseResult>() {
        // 自定义响应处理
        public ResponseResult handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
            int code = response.getStatusLine().getStatusCode();
            String message = null;
            String result = null;
            HttpEntity entity=response.getEntity();
            if(entity!=null){
                String charset= EntityUtils.getContentCharSet(entity)==null?CHARSET_ENCODING:EntityUtils.getContentCharSet(entity);
                result = new String(EntityUtils.toByteArray(entity), charset);
            }
            return new ResponseResult(code, message, result);
        }
    };


}
